package cn.hesion.dataStructures.Stack;

import java.util.Scanner;
import java.util.Stack;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(5);
        String key ="";
        boolean loop=true;
        Scanner scanner = new Scanner(System.in);
        while (loop){
            System.out.println("show:表示显示栈");
            System.out.println("exit:表示退出程序");
            System.out.println("push:表示添加数据到栈中（）入栈");
            System.out.println("pop:表示从栈取出数据（出栈）");
            key=scanner.next();
            switch (key){
                case "show":
                    stack.showStack();
                    break;
                case "push":
                    System.out.println("进入入栈操作：");
                    System.out.println("请输入一个数字：");
                    int value=scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    System.out.println("进入出栈操作");
                    try {
                        System.out.println("出栈元素为:"+stack.pop());
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
                case "exit":
                    scanner.close();
                    loop=false;
                    break;
                default:
                    break;


            }

        }
        System.out.println("程序退出，再见！");
    }
}

class ArrayStack {
    private int maxSize; // 栈的最大容量
    private int[] stack; //数组，数组模拟栈
    private int top = -1;//top表示栈顶，初始化-1

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //栈空
    public boolean isEmpty() {
        return top == -1;
    }

    //入栈
    public void push(int value){
        if(isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top]=value;
    }

    public int pop(){
        //判断栈空
        if(isEmpty()){
            throw  new RuntimeException("栈空");
        }
        int value=stack[top];
        top--;
        return value;
    }
    //注意遍历时的方向 从栈顶开始输出数据
    public void showStack(){
        if(isEmpty()){
            System.out.println("栈为空，没有数据");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }
}
